package serverManager;

import org.mortbay.util.ajax.Continuation;

import os_listener.ServerUpdates;

/**
 * this class is the class that stores all the users continuation
 */
public class ConnectionsKeeper 
{
	/**
	 * A handle to the unique ConnectionsKeeper instance.
	 */
	static private ConnectionsKeeper instance = null;
	//for the singleton
	private static Object someObject=new Object();
	Continuation[] connections;
	ServerUpdates newest_su;

	// a getter of this class
	public ServerUpdates getNewest_su() 
	{
		return newest_su;
	}

	// a setter of this class
	public void setNewest_su(ServerUpdates newest_su)
	{
		this.newest_su = newest_su;
	}

	/*
	 * this is the private constructor of this class
	 */
	private ConnectionsKeeper()
	{
		connections = new Continuation[100];
		// zeroing the array
		for (int i = 1; i < connections.length; i++) 
		{
			connections[i] = null;
		}
	}

	// a getter of this class
	public Continuation getConnection(long userId) 
	{
		return connections[(int) userId];
	}

	/**
	 * @param cc - the new continuation to add to the array
	 * @param userId - the index of this user in the array
	 * @return - true if success, false otherwise
	 */
	public boolean addConnection(Continuation cc, long userId)
	{
		// the case that there is free space for this user
		if(userId < 100)
		{
			this.connections[(int) userId] =  cc;
			return true;
		}
		return false;
	}

	/**
	 * @return The unique instance of this class.
	 */
	static public ConnectionsKeeper getInstance()
	{
		if(null == instance) 
		{
			//to insure that the time slice doesn't cause the creation of 2 instances
			synchronized (someObject) 
			{
				if (null == instance)
					instance = new ConnectionsKeeper();
			}
		}
	    return instance;
	}
}
